package org.arcg_learn.spring_cloud.scn_homework.service_gateway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class TokenVerifyFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        List<HttpCookie> cookies = request.getCookies().get("token");
        String value = cookies.get(0).getValue();
        Boolean hasKey = stringRedisTemplate.hasKey("auth:" + value);
        if (!hasKey) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            String data = "unauthorized!";
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer wrappedData = dataBufferFactory.wrap(data.getBytes());
            return response.writeWith(Mono.just(wrappedData));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
